<template>
  <el-dialog :model-value="dialogVisible" @close="closeDialog" title="编辑账号" :center="true"
             :close-on-click-modal="false" :width="500">
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="ruleForm.name"/>
      </el-form-item>
      <el-form-item label="职位" prop="ground">
        <el-select v-model="ruleForm.ground" placeholder="请选择一个职位">
          <el-option label="超级管理员" value="超级管理员"/>
          <el-option label="普通管理员" value="普通管理员"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          编辑
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref, defineProps, defineEmits, watchEffect} from 'vue'
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'

const prpos = defineProps(['dialogVisible', 'editData'])

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const ruleForm = ref({
  name: '',
  ground: '',
  date: '',
})

//监视传过来的值
watchEffect(() => {
  if (prpos.editData) {
    ruleForm.value.name = prpos.editData.name
    ruleForm.value.ground = prpos.editData.ground
    ruleForm.value.date = prpos.editData.date
  }
})


interface RuleForm {
  name: string
  ground: string
}

const rules = reactive<FormRules<RuleForm>>({
  name: [
    {required: true, message: '请输入你的密码', trigger: 'blur'},
    {min: 3, max: 5, message: '长度必须在3到5之间', trigger: 'blur'},
  ],
  ground: [
    {
      required: true,
      message: '请选择一个',
      trigger: 'change',
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      emit('edit-data', ruleForm.value)
      //关闭弹窗
      closeDialog()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  ruleForm.value.name = ''
  ruleForm.value.ground = ''
}

const options = Array.from({length: 10000}).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

//closeDialog
function closeDialog() {
  emit('close-mask', false)
}


//子组件向父组件传值
const emit = defineEmits(['close-mask', 'edit-data'])
</script>


<style scoped>
</style>